package com.polaris.live.utils

import android.view.View
import android.view.ViewGroup
import androidx.viewpager2.widget.ViewPager2
import com.polaris.live.R
import com.polaris.live.widget.avatar.AvatarView

/**
 * ScaleTransformer
 *
 * @author Created by 半仙 on 2023/10/23/023 11:54
 */
class ScaleTransformer : ViewPager2.PageTransformer {
    companion object {
        private const val MIN_SCALE = 0.8f
        private const val MIN_ALPHA = 0.8f
        private const val MARGIN_HORIZONTAL = 5 // 边距大小，单位为像素
    }

    override fun transformPage(page: View, position: Float) {
        if (page == null) return
        val absPosition = Math.abs(position)
        val scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - absPosition)

        val imageView = page.findViewById<AvatarView>(R.id.item_head)
        if (imageView == null) return
        imageView.scaleX = scaleFactor
        imageView.scaleY = scaleFactor

        // 计算空出的宽度和页面的宽度
        val extraWidth = (page.width * (1 - scaleFactor) / 2).toInt()
        val pageWidth = (page.width * scaleFactor).toInt()

        // 设置边距
        val layoutParams = page.layoutParams as ViewGroup.MarginLayoutParams
        if (position < 0) { // 前一页
            layoutParams.leftMargin = MARGIN_HORIZONTAL - extraWidth
            layoutParams.rightMargin = MARGIN_HORIZONTAL + extraWidth
        } else if (position > 0) { // 后一页
            layoutParams.leftMargin = MARGIN_HORIZONTAL + extraWidth
            layoutParams.rightMargin = MARGIN_HORIZONTAL - extraWidth
        } else { // 当前页
            layoutParams.leftMargin = MARGIN_HORIZONTAL
            layoutParams.rightMargin = MARGIN_HORIZONTAL
        }
        page.layoutParams = layoutParams

        page.alpha = MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA)
    }
}